const admZip = require('adm-zip');
const fs = require('fs');
const fsPromises = require('fs/promises');
const path = require('path');   
/**
 * 
 * @param {*} zipFile 
 * @param {*} destFolder 
 * @param {*} callback 
 * @returns 
 */
function unzip(zipFile, destFolder, callback) {
    try {
        const zip = new admZip(zipFile);
        isFileExisted(destFolder).then(res => {
            //文件夹是否存在
            res ? clearDir(destFolder) : fs.mkdirSync(destFolder);
            zip.extractAllToAsync(destFolder, true, (e) => {
                !e && callback(destFolder)
            });
        })
    } catch (error) {
        console.error(error);
    }
}

function zip(destFolder, callback) {
    try {
        const zip = new admZip();
        const outputZipPath = `${destFolder}.zip`;
        zip.addLocalFolderAsync(destFolder, (s => {
            s && zip.writeZip(outputZipPath, (err) => {
                callback(zip.toBuffer(), outputZipPath, err)
            })

        }));

    } catch (error) {
        console.error(error);
    }
}


/**
 * 删除文件夹下所有文件及将文件夹下所有文件清空
 * @param {*} path 
 */
function emptyDir(path) {
    const files = fs.readdirSync(path);
    files.forEach(file => {
        const filePath = `${path}/${file}`;
        const stats = fs.statSync(filePath);
        if (stats.isDirectory()) {
            emptyDir(filePath);
        } else {
            fs.unlinkSync(filePath);
            console.log(`删除${file}文件成功`);
        }
    });
}

/**
 * 删除指定路径下的所有空文件夹
 * @param {*} path 
 */
function rmEmptyDir(path, level = 0) {
    const files = fs.readdirSync(path);
    if (files.length > 0) {
        let tempFile = 0;
        files.forEach(file => {
            tempFile++;
            rmEmptyDir(`${path}/${file}`, 1);
        });
        if (tempFile === files.length && level !== 0) {
            fs.rmdirSync(path);
        }
    }
    else {
        level !== 0 && fs.rmdirSync(path);
    }
}

/**
 * 清空指定路径下的所有文件及文件夹
 * @param {*} path 
 */
function clearDir(path) {
    emptyDir(path);
    rmEmptyDir(path);
}

function isFileExisted(path_way) {
    return new Promise((resolve, reject) => {
        fs.access(path_way, (err) => {
            if (err) {
                resolve(false);//"不存在"
            } else {
                resolve(true);//"存在"
            }
        })
    })
}

function mkdirFiles(filePath) {
    return CommonUtil.isFileExisted(filePath).then(res => {
        if (res) {
            emptyDir(filePath)
        }
        else {
            fs.mkdirSync(filePath);
        }
    })

}


function getLocalIP() {
    const os = require('os');
    const ifaces = os.networkInterfaces()

    for (var dev in ifaces) {
        let iface = ifaces[dev]

        for (let i = 0; i < iface.length; i++) {
            let { family, address, internal } = iface[i]

            if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
                return address
            }
        }
    }
}

// 遍历文件夹的函数  
async function traverseDirectory(dirPath, readFileCallBack) {  
    try {  
        const files = await fsPromises.readdir(dirPath, { withFileTypes: true });  
  
        for (const file of files) {  
            const res = path.resolve(dirPath, file.name);  
  
            if (file.isDirectory()) {  
                // 如果是目录，递归遍历  
                await traverseDirectory(res,readFileCallBack);  
            } else {  
                // 如果是文件，打印文件路径或执行其他操作  
                readFileCallBack && readFileCallBack(res);
                console.log(`Found file: ${res}`);  
            }  
        }  
  
        console.log(`Traversal of directory ${dirPath} completed.`);  
    } catch (err) {  
        console.error(`Error traversing directory ${dirPath}:`, err);  
    }  
}  

const CommonUtil = {
    isFileExisted,
    mkdirFiles,
    clearDir,
    unzip,
    zip,
    getLocalIP,
    traverseDirectory
}

module.exports = CommonUtil